<template>
  <el-dialog :close-on-click-modal="false" title="文件导入" :before-close="handleClose" :visible.sync="dialogVisible" width="40%">
    <div class="excel-reader">
      <h2>Excel 文件读取器</h2>

      <div class="controls">
        <input type="file" ref="fileInput" @change="handleFileChange" accept=".xlsx, .xls" />
        <button class="button" @click="readExcel">读取Excel</button>
      </div>

      <div v-if="loading" class="loading">加载中...</div>

      <div v-if="error" class="error">{{ error }}</div>

      <div v-if="workbookData" class="loading">加载成功!!</div>

      <!-- <div v-if="workbookData" class="excel-preview">
        <div v-for="(sheet, sheetName) in workbookData" :key="sheetName" class="sheet-container">
          <h3>{{ sheetName }}</h3>
          <table class="excel-table">
            <thead>
              <tr>
                <th v-for="(col, colIndex) in sheet.header" :key="colIndex">{{ col }}</th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="(row, rowIndex) in sheet.data" :key="rowIndex">
                <td v-for="(cell, cellIndex) in row" :key="cellIndex"
                  :style="getCellStyle(sheet.styles, rowIndex, cellIndex)">
                  {{ cell }}
                </td>
              </tr>
            </tbody>
          </table>
        </div>
      </div> -->
    </div>

    <!-- <span slot="footer" class="dialog-footer">
      <el-button type="primary" @click="submitForm()">确 定</el-button>
      <el-button @click="handleClose">取 消</el-button>
    </span> -->
  </el-dialog>
</template>

<script>
import XLSX from 'xlsx-js-style';

export default {
  name: 'ExcelReader',
  data() {
    return {
      file: null,
      workbookData: null,
      loading: false,
      error: null
    };
  },
  props: {
    dialogVisible: {
      type: Boolean,
      default: false,
    },
    dataChange: {
      type: Object,
      default: () => { return {} }
    }
  },
  methods: {
    handleFileChange(event) {
      this.file = event.target.files[0];
      this.workbookData = null;
      this.error = null;
    },

    readExcel() {
      if (!this.file) {
        this.error = '请先选择Excel文件';
        return;
      }

      this.loading = true;
      this.error = null;

      const reader = new FileReader();

      reader.onload = (e) => {
        try {
          const data = new Uint8Array(e.target.result);
          const workbook = XLSX.read(data, { type: 'array' });

          this.processWorkbook(workbook);
        } catch (err) {
          console.error('读取Excel失败:', err);
          this.error = '读取Excel文件失败: ' + err.message;
        } finally {
          this.loading = false;
        }
      };

      reader.onerror = () => {
        this.error = '文件读取失败';
        this.loading = false;
      };

      reader.readAsArrayBuffer(this.file);
    },

    processWorkbook(workbook) {
      const result = {};

      workbook.SheetNames.forEach(sheetName => {
        const worksheet = workbook.Sheets[sheetName];

        // 获取单元格范围
        const range = XLSX.utils.decode_range(worksheet['!ref']);

        // 提取数据
        const data = XLSX.utils.sheet_to_json(worksheet, { header: 1, defval: '' });

        // 提取样式
        const styles = {};
        for (let R = range.s.r; R <= range.e.r; ++R) {
          for (let C = range.s.c; C <= range.e.c; ++C) {
            const cellAddress = XLSX.utils.encode_cell({ r: R, c: C });
            if (worksheet[cellAddress] && worksheet[cellAddress].s) {
              styles[`${R},${C}`] = worksheet[cellAddress].s;
            }
          }
        }

        result[sheetName] = {
          header: data[0] || [],
          data: data.slice(1),
          styles
        };
      });

      this.workbookData = this.xlsxParseData(result);

      this.$emit("parse", this.workbookData);
    },

    // 格式处理导入的数据
    xlsxParseData(data) {
      let change = this.dataChange;
      let arrs = [];
      for (let v in data) {
        let item = data[v];
        item.header.forEach((vv, i) => {
          item.header[i] = change[item.header[i].trim()];
        });
        for (let vv of item.data) {
          let arr = {};
          vv.forEach((vvv, i) => {
            arr[item.header[i]] = vvv.trim();
          });
          arrs.push(arr);
        }
      }
      return arrs;
    },

    getCellStyle(styles, rowIndex, cellIndex) {
      // 注意: 行索引需要+1，因为第一行是表头
      const styleKey = `${rowIndex + 1},${cellIndex}`;
      const cellStyle = styles[styleKey];

      if (!cellStyle) return {};

      const cssStyle = {};

      // 背景色
      if (cellStyle.fill && cellStyle.fill.fgColor) {
        const rgb = cellStyle.fill.fgColor.rgb;
        if (rgb) {
          cssStyle.backgroundColor = `#${rgb.slice(2)}`; // 去掉开头的 'FF'
        }
      }

      // 字体颜色
      if (cellStyle.font && cellStyle.font.color) {
        const rgb = cellStyle.font.color.rgb;
        if (rgb) {
          cssStyle.color = `#${rgb.slice(2)}`;
        }
      }

      // 字体加粗
      if (cellStyle.font && cellStyle.font.bold) {
        cssStyle.fontWeight = 'bold';
      }

      // 字体倾斜
      if (cellStyle.font && cellStyle.font.italic) {
        cssStyle.fontStyle = 'italic';
      }

      // 下划线
      if (cellStyle.font && cellStyle.font.underline) {
        cssStyle.textDecoration = 'underline';
      }

      // 删除线
      if (cellStyle.font && cellStyle.font.strike) {
        cssStyle.textDecoration = 'line-through';
      }

      // 对齐方式
      if (cellStyle.alignment) {
        if (cellStyle.alignment.horizontal) {
          cssStyle.textAlign = cellStyle.alignment.horizontal;
        }
        if (cellStyle.alignment.vertical) {
          cssStyle.verticalAlign = cellStyle.alignment.vertical;
        }
      }

      // 边框
      if (cellStyle.border) {
        const borderStyles = [];

        ['top', 'bottom', 'left', 'right'].forEach(side => {
          if (cellStyle.border[side]) {
            const border = cellStyle.border[side];
            let style = 'solid'; // 默认solid
            if (border.style) {
              style = border.style === 'medium' ? 'solid' : border.style;
            }
            const color = border.color ? `#${border.color.rgb.slice(2)}` : '#000';
            borderStyles.push(`${style} 1px ${color}`);
          }
        });

        if (borderStyles.length > 0) {
          cssStyle.border = borderStyles.join(' ');
        }
      }

      return cssStyle;
    },

    // 关闭弹窗需要做的事情
    handleClose() {
      this.$emit("close");
    },
    submitForm() {
      this.$emit("submit", data);
    }
  }
};
</script>

<style scoped>
.excel-reader {
  max-width: 1000px;
  margin: 0 auto;
  padding: 20px;
  font-family: Arial, sans-serif;
}

.controls {
  margin: 20px 0;
  display: flex;
  gap: 10px;
  align-items: center;
}

.button {
  padding: 8px 16px;
  background-color: #4CAF50;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.button:hover {
  background-color: #45a049;
}

input[type="file"] {
  padding: 8px;
  border: 1px solid #ddd;
  border-radius: 4px;
}

.loading,
.error {
  padding: 10px;
  margin: 10px 0;
  border-radius: 4px;
}

.loading {
  background-color: #f0f0f0;
  color: #333;
}

.error {
  background-color: #ffdddd;
  color: #d8000c;
}

.excel-preview {
  margin-top: 20px;
  overflow-x: auto;
}

.sheet-container {
  margin-bottom: 30px;
}

.excel-table {
  width: 100%;
  border-collapse: collapse;
  margin-top: 10px;
}

.excel-table th,
.excel-table td {
  border: 1px solid #ddd;
  padding: 8px;
  text-align: left;
}

.excel-table th {
  background-color: #f2f2f2;
  color: #333;
  font-weight: bold;
}

.excel-table tr:nth-child(even) {
  background-color: #f9f9f9;
}

.excel-table tr:hover {
  background-color: #f1f1f1;
}
</style>